<template>
  <div class="good">
    <div class="mybody">
      <!-- 标题和新增按钮 -->
      <div class="header">
        <el-button type="success" @click="handleAdd">新增分类</el-button>
      </div>

      <!-- 表单 -->
      <el-form class="mytable">
        <el-table :data="paginatedData" border stripe style="width: 100%" ref="tableRef" align="center" v-loading="loading">
          <el-table-column label="ID" width="80" prop="id" align="center" />
          <el-table-column label="分类名称" prop="name" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        class="AddGood"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="sizes, prev, pager, next"
        :total="totalItems"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="50%"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, inject, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 注入axios
const $axios = inject('$axios');

// 数据定义
const categoryList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('新增分类');
const formRef = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = computed(() => categoryList.value.length);

// 根据分页计算当前显示的数据
const paginatedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return categoryList.value.slice(startIndex, endIndex);
});

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  // 如果当前页没有数据，则回到第一页
  if ((currentPage.value - 1) * pageSize.value >= totalItems.value) {
    currentPage.value = 1;
  }
};

// 表单数据
const form = reactive({
  id: null,
  name: ''
});

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ]
});

// 获取所有分类
const fetchCategories = async () => {
  loading.value = true;
  try {
    const response = await $axios.get('/api/category');
    if (response.code === '200') {
      categoryList.value = response.data;
    } else {
      ElMessage.error('获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表出错:', error);
    ElMessage.error('获取分类列表出错');
  } finally {
    loading.value = false;
  }
};

// 新增分类
const handleAdd = () => {
  form.id = null;
  form.name = '';
  if (formRef.value) {
    formRef.value.resetFields();
  }
  dialogTitle.value = '新增分类';
  dialogVisible.value = true;
};

// 编辑分类
const handleEdit = (row) => {
  resetForm();
  dialogTitle.value = '编辑分类';
  form.id = row.id;
  form.name = row.name;
  dialogVisible.value = true;
};

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await $axios.get(`/api/category/delete?id=${row.id}`);
      if (response.code === '200' || response.success) {
        ElMessage.success('删除成功');
        fetchCategories();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除分类出错:', error);
      ElMessage.error('删除分类出错');
    }
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除操作');
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    let url = '/api/category';
    let method = 'post';
    
    if (form.id) {
      // 编辑
      method = 'put';
    }
    
    const response = await $axios[method](url, form);
    
    if (response.code === '200' || response.success) {
      ElMessage.success(form.id ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      // 清空表单数据
      form.id = null;
      form.name = '';
      fetchCategories();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    ElMessage.error('提交表单出错');
  }
};

// 重置表单
const resetForm = () => {
  form.id = null;
  form.name = '';
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.good {
  padding: 30px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.mybody {
  width: 100%;
  padding: 0;
}

.header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
}

.mytable {
  text-align: center;
  width: 100%;
}

.demo-pagination-block {
  margin-top: 20px;
  text-align: center;
}

/* 按钮样式 */
.good .mytable :deep(button>span) {
  color: white;
  font-family: "黑体";
}

/* 表格样式优化 */
:deep(.el-table) {
  width: 100%;
}

:deep(.el-form) {
  width: 100%;
  margin: 0;
  padding: 0;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>